var io = require('socket.io')();
var crud = require('crud');
var read = require('segment/read');

io.on('connection', function (_socket) {
  console.log(' socket 连接创建成功 ');

  // 推送

  read.readText(function(list) {

    // 初始化数据库连接
    crud.init('chat');

    list.map(function(item) {
      crud.append(item, function() {});
    });

    crud.query({}, function(result) {
      console.log('查询成功');
      io.emit('chat message', JSON.stringify(result));
      console.log(JSON.stringify(result));
    });
  });

  // 接收
  // _socket.on('chat message', function(msg){
  //   console.log('message: ' + msg);
  //
  // });
});

module.exports = {
  listen: function (_server) {
    return io.listen(_server);
  }
}
